<template>
  <span>{{numTween}}</span>
</template>

<script>
import TWEEN from "@tweenjs/tween.js";
export default {
  name: "AnimatedNumber",
  props: {
    num: {
      type: [Number, String],
      default: 0
    },
    t: {
      type: Number,
      default: 500
    }
  },
  data() {
    return {
      numTween: 0
    };
  },
  methods: {
    changeNum(newValue, oldValue) {
      new TWEEN.Tween({
        number: oldValue
      })
        .to(
          {
            number: newValue
          },
          this.t
        )
        .onUpdate(tween => {
          this.numTween = tween.number.toFixed(0);
        })
        .start();
      function animate() {
        if (TWEEN.update()) {
          requestAnimationFrame(animate);
        }
      }
      animate();
    }
  },
  watch: {
    num(newValue, oldValue) {
      this.changeNum(newValue, oldValue);
    }
  },
  created() {
    this.changeNum(this.num, 0);
  }
};
</script>